<?php
/**
 * KePHP, Keep PHP easy!
 */

namespace Gitee\Db\Gitee;

use Ke\Adm\Model;

/**
 * Class App_Token
 * tableName 'gitee_app_token'
 *
 * // class properties
 *
 * @property int    $id            主键
 * @property int    $app_id        app_id
 * @property string $access_token  access_token
 * @property string $token_type    token_type
 * @property int    $expires_in    expires_in
 * @property string $refresh_token refresh_token
 * @property mixed  $scope         scope
 * @property int    $created_at    created_at
 * // class properties
 */
class App_Token extends Model
{
	
	protected static $cacheSource = 'default';
	
	protected static $pk = 'id';
	
	protected static $pkAutoInc = true;
	
	protected static $tableName = 'gitee_app_token';
	
	protected static $columns = [];
	
	public static function dbColumns()
	{
		// database columns
		return [
			'id'            => ['label' => '主键', 'int' => 1, 'pk' => 1, 'autoInc' => 1],
			'app_id'        => ['int' => 1],
			'access_token'  => ['max' => 32, 'default' => ''],
			'token_type'    => ['max' => 16, 'default' => ''],
			'expires_in'    => ['int' => 1],
			'refresh_token' => ['max' => 64, 'default' => ''],
			'scope'         => [],
			'created_at'    => ['timestamp' => 1, self::ON_CREATE => 'now'],
		];
		// database columns
	}
	
	public function isValid(App $app = null)
	{
		if ($this->isNew()) return false;
		$now = time();
		if ($now > $this->created_at + $this->expires_in) return false; // 超时
		if (isset($app) && !$this->isBelongTo($app)) return false;
		return true;
	}
	
	public function isBelongTo(App $app)
	{
		if ($this->isNew() || $app->isNew()) return false;
		if (empty($this->app_id)) return false;
		if ($this->app_id !== $app->getPk()) return false;
		return true;
	}
}
